package org.rc.task;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import org.rc.dao.AthleteDao;
import org.rc.model.Athlete;
import org.rc.model.Race;
import org.rc.six.DataStoreIndexDao;
import org.rc.six.Document;
import org.rc.six.IndexerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl;

/**
 * Re index all Athletes in the datastore {@link Race}
 * @author dokeeffe
 */
public class ReIndexAthletesTask extends Task {

    private static final Logger LOGGER = LoggerFactory.getLogger(ReIndexAthletesTask.class);
    private AthleteDao athleteDao = new AthleteDao();
    private IndexerService indexerService = new IndexerService(new DataStoreIndexDao());

    /**
     * Re index all athletes 100 at a time. After each 100 spawn a nre task.
     * Re indexes by creating a new {@link Document} and adding to the {@link IndexerService}
     * @param parameterMap
     */
    @Override
    public void run(Map parameterMap) {
        String startCursor = getFirstArrayParam(parameterMap, "cursor");
        List<Athlete> results = new ArrayList<Athlete>();
        String newCursor = athleteDao.getAllFromCursor(results, startCursor, 100);
        for (Athlete a : results) {
            String name = a.getFirstName() + " " + a.getSecondName();
            Document doc = new Document("Athlete("+a.getId().toString()+")", name, null);
            indexerService.index(doc);
        }
        if (!results.isEmpty()) {
            resubmit(newCursor);
        }
    }

    /**
     * Re spawn a new task from the newCursor passed
     * @param newCursor
     */
    private void resubmit(String newCursor) {
        LOGGER.debug("spawning new indexer task");
        Queue queue = QueueFactory.getDefaultQueue();
        queue.add(withUrl("/admin?task="+getTaskName()+"&cursor=" + newCursor).method(TaskOptions.Method.GET));
        
    }

    @Override
    public String getUiName() {
        return "Reindex Athletes";
    }

}
